import { DataSource } from 'typeorm';
import * as bcrypt from 'bcryptjs';
import { User } from '../users/users.entity';

async function hashExistingPasswords(dataSource: DataSource) {
  const userRepo = dataSource.getRepository(User);
  const users = await userRepo.find();

  const saltRounds = 10;

  for (const user of users) {
    // 防止重复哈希：判断是否已经是 bcrypt 格式
    if (!user.password.startsWith('$2b$')) {
      user.password = await bcrypt.hash(user.password, saltRounds);
      await userRepo.save(user);
      console.log(`Hashed password for user ${user.phone}`);
    }
  }

  console.log('All passwords have been hashed!');
}

export default hashExistingPasswords;
